package com.bupt.kgplatform.config.HandlerInterceptor;

import com.bupt.kgplatform.Util.GetNowTime;
import com.bupt.kgplatform.Util.RedisCache;
import com.bupt.kgplatform.Util.UserHolder;
import com.bupt.kgplatform.entity.Log;
import com.bupt.kgplatform.entity.User;
import com.bupt.kgplatform.mapper.LogMapper;
import com.bupt.kgplatform.mapper.UserMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * LoginHandlerInterceptor
 *
 * @author zrz
 * @date 2024/5/20
 * @time 12:54
 * @Description 登录拦截器
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private final RedisCache redisCache;

    private final UserMapper userMapper;
    private final GetNowTime getNowTime;
    private final LogMapper logMapper;

    public RefreshTokenInterceptor(RedisCache redisCache, UserMapper userMapper, GetNowTime getNowTime, LogMapper logMapper){
        this.redisCache = redisCache;
        this.userMapper = userMapper;
        this.getNowTime = getNowTime;
        this.logMapper = logMapper;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的信息
        String token = request.getHeader("authorization");
        if (token == null) {
            return true;
        }
        //获得redis中的用户信息
        Object userIds = redisCache.getCacheObject(token);
        //判断用户是否存在
        if (userIds == null) {
            return true;
        }
        int userId = Integer.parseInt(userIds.toString());
        //用户存在，保存用户信息到threadlocal
        UserHolder.setUser(userId);
        //刷新redis有效期
        redisCache.expire(token,1, TimeUnit.DAYS);
        //放行
        String requestPath = request.getRequestURI();
        Log log = new Log();
        log.setCreateTime(getNowTime.getStringTime());
        log.setContent(requestPath);
        log.setUserId(userId);
        User user = userMapper.selectById(userId);
        log.setUserName(user.getUserName());
        logMapper.insert(log);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除user，防止用户信息泄露
        UserHolder.removeUser();
    }

}
